from decimal import Decimal

3from django.http import JsonResponse
from django.views import View
from django_redis import get_redis_connection
from redis import Redis

from apps.areas.models import Address
from apps.goods.models import SKU
from utils.views import LoginRequiredJSONMixin

class OrderSettlementView(LoginRequiredJSONMixin, View):
    """结算订单"""

    def get(self, request):
        """提供订单结算页面"""
        # 获取登录用户
        user = request.user
        # 从redis里取出skuid
        redis_conn: Redis = get_redis_connection('carts')
        # 获取hash的数据
        redis_carts = redis_conn.hgetall('carts_%s' % user.id)
        # 获取set里的数据
        carts_selected = redis_conn.smembers('selected_%s' % user.id)
        # 把redis取出的数据 重新 放到一个新的字典里 包括他的数量
        cart_data = {}
        for sku_id in carts_selected:
            cart_data[int(sku_id)] = int(redis_carts[sku_id])

        skus = SKU.objects.filter(id__in=cart_data.keys())

        sku_list = []
        for sku in skus:
            sku_list.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,  # 图片
                'name': sku.name,  # 名字
                'price': sku.price,  #
                'count': cart_data[sku.id],  # 数量
            })
        print('sku_list',sku_list)
        # 运费 这里固定位10元
        freight = Decimal('10.00')  # 运费
        # 获取所有的用户的地址信息
        addrs = Address.objects.filter(user=user, is_deleted=False)
        addrs_list = []
        for addr in addrs:
            addrs_list.append({
                'province': addr.province.name,
                'city': addr.city.name,
                'district': addr.district.name,
                'place': addr.place,
                'receiver': addr.receiver,
                'mobile': addr.mobile,
                'id': addr.id,

            })
        # 拼接json返回

        context = {
            'skus': sku_list,
            'freight': freight,
            'addresses': addrs_list,
            'default_address_id': request.user.default_address,
        }

        return JsonResponse({"context": context, 'code': 0, 'errmsg': 'ok'})
